import React, { Component } from "react";
import { Button, StyleSheet, Text, View, FlatList, RefreshControl, ActivityIndicator } from "react-native";
// import keys from '../res/data/langs.json'
import NavigationBar from 'react-native-navbar-plus';
import { tabNav } from "../navigator/NavigationDelegate";
import actions from "../action";
import { connect } from "react-redux";
import DataStore, { FLAG_STORAGE } from '../expand/dao/DataStore';
import NavigationUtil from "../navigator/NavigationUtil";
import TrendingItem from '../common/TrendingItem'
import Toast from 'react-native-easy-toast';
import FavoriteDao from "../expand/dao/FavoriteDao";
import FavoriteUtil from "../util/FavoriteUtil";
import EventBus from 'react-native-event-bus'
import EventTypes from '../util/EventTypes';
import { FLAG_LANGUAGE } from '../expand/dao/LanguageDao'
import ArrayUtil from "../util/ArrayUtil";
const favoriteDao = new FavoriteDao(FLAG_STORAGE.flag_trending)
const URL = 'https://github.com/trending/';
const QUERY_STR = '&sort=stars'
const THEME_COLOR = 'red'

class TrendingPage extends Component {
  constructor(props) {
    super(props)
    const { onLoadLanguage } = this.props
    onLoadLanguage(FLAG_LANGUAGE.flag_language)
  }

  _tabNav() {
    const { theme, keys } = this.props;
    //注意：主题发生变化需要重新渲染top tab
    if (
      theme !== this.theme || !this.tabNav ||
      !ArrayUtil.isEqual(this.preKeys, keys)) {
      //优化效率：根据需要选择是否重新创建建TabNavigator，通常tab改变后才重新创建
      this.theme = theme;
      this.preKeys = keys;
      this.tabNav = tabNav({
        Component: TrendingTabPage,
        keys,
        theme
      });
    }
    return this.tabNav;
  }

  render() {
    const { theme: { themeColor } = {}, keys, theme } = this.props;
    let statusBar = {
      backgroundColor: themeColor,
      barStyle: 'light-content'
    }


    let navigationBar = <NavigationBar
      title="趋势"
      style={{ backgroundColor: theme.themeColor }}
      statusBar={statusBar}
    />

    // themeColor: '#2196f3'
    const TabNavigator = keys.length ? this._tabNav() : null;
    return (
      <View style={styles.container}>
        {navigationBar}
        {TabNavigator}
      </View>
    )
  }
}

const mapTrendingStateToProps = (state) => ({
  theme: state.theme.theme,
  keys: state.language.languages,
})

const mapTrendingDispatchToProps = dispatch => ({
  onLoadLanguage: (flag) => dispatch(actions.onLoadLanguage(flag))
});

export default connect(mapTrendingStateToProps, mapTrendingDispatchToProps)(TrendingPage);


const pageSize = 10 //设为常量,防止修改
class TrendingTab extends Component {
  constructor(props) {
    super(props);
    const { tabLabel } = this.props
    this.storeName = tabLabel
    this.isFavoriteChanged = false;
  }

  componentDidMount() {
    this.loadData();
    EventBus.getInstance().addListener(EventTypes.favoriteChanged_trending, this.favoriteChangeListener = () => {
      this.isFavoriteChanged = true;
    });
    EventBus.getInstance().addListener(EventTypes.bottom_tab_select, this.bottomTabSelectListener = (data) => {
      if (data.to === 1 && this.isFavoriteChanged) {
        this.loadData(null, true);
      }
    })
  }

  componentWillUnmount() {
    EventBus.getInstance().removeListener(this.favoriteChangeListener);
    EventBus.getInstance().removeListener(this.bottomTabSelectListener);
  }

  loadData(LoadMore, refreshFavorite) {
    const { onRefreshTrending, onLoadMoreTrending, onFlushTrendingFavorite } = this.props;
    const store = this._store();
    const url = this.genFetchUrl(this.storeName)
    if (LoadMore) {
      onLoadMoreTrending(this.storeName, ++store.pageIndex, pageSize, store.items, favoriteDao, callBack => {
        this.refs.toast.show('没有更多了')
        // Alert('没有更多了')
        console.log('没有更多了')
      })
    } else if (refreshFavorite) {
      onFlushTrendingFavorite(this.storeName, store.pageIndex, pageSize, store.items, favoriteDao);
    } else {
      onRefreshTrending(this.storeName, url, pageSize, favoriteDao)
    }
  }

  /**
   * 获取与当前页面相关的数据
   * @returns 
   */

  _store() {
    const { trending } = this.props;
    let store = trending[this.storeName]
    if (!store) {
      store = {
        items: [],
        isLoading: false,
        projectModels: [], //要显示的数据
        hideLoadingMore: true,//默认隐藏加载更多
      }
    }
    return store
  }

  genFetchUrl(key) {
    return URL + key + '?since=daily';
  }

  renderItem(data) {
    const item = data.item
    const { theme } = this.props;
    return <TrendingItem
      projectModel={item}
      theme={theme}
      onSelect={(callBack) => {
        NavigationUtil.goPage({
          theme,
          projectModels: item,
          flag: FLAG_STORAGE.flag_trending,
          callBack
        }, 'DetailPage')
      }}
      onFavorite={(item, isFavorite) => FavoriteUtil.onFavorite(favoriteDao, item, isFavorite, FLAG_STORAGE.flag_trending)}
    />
  }

  genIndicator() {
    return this._store().hideLoadingMore ? null :
      <View style={styles.indicatorContainer}>
        <ActivityIndicator
          style={styles.indicator}
        />
        <Text>正在加载更多...</Text>
      </View>
  }
  render() {
    let store = this._store();
    if (!store) {
      store = {
        list: [],
        isLoading: false
      }
    }
    return (<View style={styles.container}>
      <FlatList
        data={store.projectModels}
        renderItem={data => this.renderItem(data)}
        keyExtractor={item => '' + item.item.id}
        refreshControl={
          <RefreshControl
            title="Loading"
            titleColor={THEME_COLOR}
            colors={[THEME_COLOR]}
            refreshing={store.isLoading}
            onRefresh={() => this.loadData()}
            tintColor={THEME_COLOR}
          />
        }
        ListFooterComponent={() => this.genIndicator()}
        onEndReached={() => {
          // 第一次进入页面的时候不应该加载更多, ==优化==  原因是列表每次滚动的时候每次调用两次
          if (this.canLoadMore) {
            setTimeout(() => {
              this.loadData(true)
              this.canLoadMore = false
            }, 100);
          }
        }}
        onEndReachedThreshold={0.5}
        onMomentumScrollBegin={() => {
          this.canLoadMore = true; //fix 初始化滚动调用onEndReached的问题
          console.log('---onMomentumScrollBegin---')
        }}
      />
      <Toast
        ref={'toast'}
        position={'center'}
      />
    </View>);
  }
}

const mapStateToProps = (state) => ({
  trending: state.trending,
})
const mapDispatchToProps = (dispatch) => ({
  onRefreshTrending: (storeName, url, pageSize, favoriteDao) => dispatch(actions.onRefreshTrending(storeName, url, pageSize, favoriteDao)),
  onLoadMoreTrending: (storeName, pageIndex, pageSize, items, favoriteDao, callBack) => dispatch(actions.onLoadMoreTrending(storeName, pageIndex, pageSize, items, favoriteDao, callBack)),
  onFlushTrendingFavorite: (storeName, pageIndex, pageSize, items, favoriteDao,) => dispatch(actions.onFlushTrendingFavorite(storeName, pageIndex, pageSize, items, favoriteDao,))
})

const TrendingTabPage = connect(mapStateToProps, mapDispatchToProps)(TrendingTab)


const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  indicatorContainer: {
    alignItems: 'center'
  },
  indicator: {
    color: 'red',
    margin: 10
  }
})